import Taro, {Component} from '@tarojs/taro'

import {View} from "@tarojs/components"
import './index.scss'
import {AtButton, AtInput} from "taro-ui";
import {getGlobalData} from "../../../global.d";
import {createFiles} from "./service";



export default class Index extends Component {

    constructor(props) {
        super(props);
        this.state = {
          title:'',
          fileID:'',
          file:'',
        }
    }
  componentWillMount(){
    this.setState({

    })
    Taro.setNavigationBarTitle({
      title:'上传文件'
    })
  }
  handleChange (key,value) {
    this.setState({
      [key]: value
    });
  }
  async setFileID(cloudPath,filePath){
    await this.getFileId(cloudPath,filePath).then(res=>{
      this.state.fileID = res
      const user = getGlobalData('user');
      const myjson = {'user':user._id,
        'title': this.state.title,
        'fileID':this.state.fileID,
        'classKey':user.userLastTimeClass.classKey
      }
      createFiles(myjson)
    })

  }
  /*异步函数，获取fileID*/
  async getFileId(cloudPath,filePath){
    let fileID = ''
    await wx.cloud.uploadFile({
      cloudPath: cloudPath ,
      filePath: filePath,
    }).then(res => {
      fileID = res.fileID
    })
    console.log('在函数中的fileID是',fileID)
    return fileID
    resolve()
  }

    SubmitFile () {
      wx.chooseMessageFile({
      count: 10,
      type: 'file',
      success: res =>{
        console.log('成功',res)
        let file = res.tempFiles
        this.state.file = file[0].path
        /*console.log('第二',this.state.file,'----')*/
      }
    })
  }
  Submit(){
    let myDate = new Date()
    const filePath = this.state.file
    /*正则表达式，匹配图片后缀上传图片*/
    /*使用当前时间戳作为图片名字，保证图片不会被覆盖*/
    const cloudPath = 'files/'+myDate.getTime()+filePath.match(/\.[^.]+?$/)[0]
    this.setFileID(cloudPath,filePath)
  }
    render() {

        return (
          <View>
          <AtInput
            name='title'
            title='标题'
            type='text'
            placeholder='文件标题'
            value={this.state.title}
            onChange={this.handleChange.bind(this, 'title')}
          />
          {/*上传文件按钮*/}
          <AtButton onClick={this.SubmitFile.bind(this)}>选择文件</AtButton>
            <AtButton onClick={this.Submit.bind(this)}>上传</AtButton>
          </View>
        )
    }

}
